package com.zit.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zit.dao.BerthDAO;
import com.zit.dao.StudentDAO;
import com.zit.entity.Classes;
import com.zit.entity.Student;

public class StudentService extends BaseService {
	
	private StudentDAO studentDao=new StudentDAO();
	
	private BerthDAO berthDao=new BerthDAO();
	
	/**
	 * 查询所有学生信息
	 * @param student
	 * @param s
	 * @return
	 */
	public List<Student> select(Student student){
		Session s = null;
		Transaction tx = null ;
		List<Student> students=new ArrayList<Student>();;
		try {
			s = getSession();
			tx = s.beginTransaction();
			students=studentDao.select(student, s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
		return students;
	}
	
	/**
	 * 查询学生信息
	 * @param student
	 * @param s
	 * @return
	 */
	public Student selectAStudent(Student student){
		Session s = null;
		Transaction tx = null ;
		Student stu=null;
		try {
			s = getSession();
			tx = s.beginTransaction();
			stu=studentDao.selectAStudent(student, s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
		return stu;
	}
	
	/**
	 * 查询对应学期对应专业的班级
	 * @param student
	 * @param s
	 * @return
	 */
	public List<Classes> select(int tid,int pid){
		Session s = null;
		Transaction tx = null ;
		List<Classes> classes=new ArrayList<Classes>();;
		try {
			s = getSession();
			tx = s.beginTransaction();
			classes=studentDao.select(tid,pid, s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
		return classes;
	}
	
	/**
	 * 添加学生并把床位设为有人
	 * @param student
	 */
	public void add(Student student){
		Session s = null;
		Transaction tx = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			studentDao.saveStudent(student, s);
			berthDao.updateBerth(student.getBerth(), s);
			tx.commit();
		} catch (Exception e){
			e.printStackTrace();
			tx.rollback();
		}finally{
			s.close();
		}
	}
	
	/**
	 * 作者：王冲
	 * 功能：删除学生
	 * @param student
	 */
	public void deleteStudent(Student student){
		Session s = null;
		Transaction tx = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			studentDao.deleteStudent(student, s);
			berthDao.updateBerth(student.getBerth(), s);
			tx.commit();
		} catch (Exception e){
			e.printStackTrace();
			tx.rollback();
		}finally{
			s.close();
		}
	}
	
	public static void main(String[] args) {
		StudentService studentservice=new StudentService();
		Student student=new Student();
		student.setName("王");
		List<Student> list = studentservice.select(student);
		for (Student s : list) {
			System.out.println(s.getName());
		}
	}
}
